/**
 * @author: Jone
 * @update: 2019-12-10
 * @version: 2.6
 * 支持平台：changyou(畅游) phone(手机) warframe(星际战甲) wechat(微信) cyou3(橙柚三联) changyouwg(海战世界)
 **/
'use strict';
(function (window) {
    var that,

        name = 'ja',

        version = '2.6',

        arrHost = ['kzgj.cy.com'],      // 访问域名使用通用域名下接口 http://join-activity.changyou.com

        urlWxBind = '//tlus.changyou.com/xtl/wxBind/20180910/mobile/index.html',    // 微信账号绑定链接

        isIos = /iphone|ipod|ipad/i.test(window.navigator.userAgent.toLowerCase()),

        isMobile = /Android|webOS|iPhone|iPad|iPod|BlackBerry|IEMobile|Opera Mini/i.test(navigator.userAgent),

        isWechat = window.navigator.userAgent.toLowerCase().match(/MicroMessenger/i) == 'micromessenger',

        isLongmen = location.href.indexOf('/longmen/') !== -1;

    /**
     * == 全局对象 ==
     * 注：code 为初始化状态：0 初始化未完成;1 初始化完成/已登录;2 初始化完成/未登录;1106 活动未开始;1103 活动已结束;1102 活动无效
     *   glob 为全局使用对象，包含多
     *   _glob 只包含初始化回调对象
     * */
    var glob = {
        type: '0'
    };
    var _glob = {
        code: undefined,    // 活动信息 landing/init 返回code
        isIos: isIos,
        isLongmen: isLongmen,
        isMobile: isMobile,
        isWechat: isWechat,
        urlWxBind: urlWxBind,
        isClosure: undefined,
        isLogin: false,
        userInfo: undefined,
        wechatInfo: undefined,
        wxBindName: undefined,      // 微信绑定账号昵称
        message: 'ok'
    };

    /**
     * == 中间件，用来管理初始化流程 ==
     * */
    var MidWare = function() {
        this.cache = [];
        this.options = {};
    };
    MidWare.prototype = {
        use: function(fn) {
            this.cache.push(fn);
            return this;
        },
        next: function(argument) {
            if(this.cache && this.cache.length > 0) {
                var ware = this.cache.shift();
                ware.call(this, this.options || {}, this.next.bind(this));
            }
        },
        handleRequest: function(options) {
            this.options = options;
            this.next();
        }
    };

    /**
     * == 工具类 ==
     * 会合并到 JoinActivity 原型链下，可通过 ja[name] 方法直接调用
     * */
    function Utils() {

    }
    Utils.prototype = {
        getQueryString: function(name) {
            var reg = new RegExp('(^|&)'+ name +'=([^&]*)(&|$)');
            var r = window.location.search.substr(1).match(reg);
            if(r != null) return  r[2]; return null;
        },
        isJSON: function(str) {
            if (typeof str == 'string') {
                try {
                    return (typeof JSON.parse(str) == 'object' && !!obj);
                } catch(e) {
                    return false;
                }
            }
        },
        objDelUndefined: function(obj) {
            var json = {};
            for(var key in obj) {
                if(obj[key]) json[key] = obj[key];
            }
            return json;
        },
        backTop: function(num, time) {
            $('html, body').animate({scrollTop: (num || 0) + 'px'}, time || 300);
        },
        isObject: function(o) {
            return (typeof o === 'object' || typeof o === 'function') && o !== null
        },
        isString: function(val) {
            return typeof val === 'string';
        },
        objType: function(val) {
            var json = {
                '[object Object]': 'object',
                '[object Array]': 'array',
                '[object Number]': 'number',
                '[object Function]': 'function',
                '[object Null]': 'null',
                '[object Undefined]': 'undefined',
                '[object Boolean]': 'boolean',
                "[object String]" : 'string'
            };
            return json[Object.prototype.toString.call(val)]
        },
        stopMove: function() {
            document.body.addEventListener('touchmove', function (e) {
                e.preventDefault(); //阻止默认的处理方式(阻止下拉滑动的效果)
            }, {passive: false});
        },
        getTwo: function(n) {
            n = n.toString();
            return n[1] ? n : "0" + n;
        },
        iphone: function() {
            if(screen.height === 812 && screen.width === 375){
                return "iphoneX";
            }else if(screen.height === 736 && screen.width === 414){
                return "iphone8P";  // 6、7、8 Plus
            }else if(screen.height === 667 && screen.width === 375){
                return "iphone8";   // 6、7、8
            }else if(screen.height === 568 && screen.width === 320){
                return "iphone5";
            }else{
                return "iphone4";
            }
        },
        setUrlParams: function(val) {
            var str = '?infoData=',
                arr = [];
            for(var key in val) {
                var value = val[key] || typeof val[key] === 'number' ? val[key] : '';
                arr.push(key + '@@@' + encodeURIComponent(value));
            }
            return str + arr.join('@@@@');
        },
        getUrlParams: function() {
            var json = {},
                info = that.utils.getQueryString('infoData');
            if(info) {
                info.split('@@@@').forEach(function(item) {
                    var key = item.split('@@@')[0],
                        val = item.split('@@@')[1];
                    json[key] = decodeURIComponent(val);
                });
            }
            return json;
        },
        formatDate: function(now) {
            now = new Date(now);
            var year = now.getFullYear();
            var month = now.getMonth() + 1;
            var date = now.getDate();
            var hour = now.getHours();
            var minute = now.getMinutes();
            var second = now.getSeconds();
            return year + "-" + month + "-" + date + " " + hour + ":" + minute + ":" + second;
        },
        longmen: function(obj) {
            var imgN = 'longmen_test.png';
            if(obj.color === 'white' || obj.color === '#fff') {
                imgN = 'longmen_test_white.png'
            }
            $('<img />').attr('src', '//i0.cy.com/xtl/logo/' + imgN).css($.extend({
                width: 80,
                position: 'absolute',
                top: 20,
                left: 20,
                zIndex: 10
            }, obj)).appendTo($(obj.parent || 'body'));
        },
        url_add_key: function(url, key, val){
            key = (key || 't') +'=';  //默认是"t"
            url = url || location.href;
            var reg = new RegExp(key+'\\d+');  //正则：t=1472286066028
            var timestamp = val || +new Date();
            if(url.indexOf(key) > -1){ //有时间戳，直接更新
                return url.replace(reg,key+timestamp);
            }else{  //没有时间戳，加上时间戳
                if(url.indexOf('\?')>-1){
                    var urlArr=url.split('\?');
                    if(urlArr[1]){
                        return urlArr[0]+'?'+key+timestamp+'&'+urlArr[1];
                    }else{
                        return urlArr[0]+'?'+key+timestamp;
                    }
                }else{
                    if(url.indexOf('#')>-1){
                        return url.split('#')[0]+'?'+key+timestamp+location.hash;
                    }else{
                        return url+'?'+key+timestamp;
                    }
                }
            }
        },
        href: function(url) {
            !isIos && isWechat ? location.replace(url) : location.href = url;
        },
        reload: function() {
            location.reload();
        },
        urlAddSearch: function(url) {
            url += (glob.urlSearch || '');
            return !isIos && isWechat ? this.url_add_key(url) : url;
        },
        // 对象深层合并
        deepMerge: function (obj1, obj2) {
            for (var key in obj2) {
                obj1[key] = obj1[key] && obj1[key].toString() === "[object Object]" ?
                    utils.deepMerge(obj1[key], obj2[key]) : obj1[key] = obj2[key];
            }
            return obj1;
        },
        // 弹窗
        win: {
            scrolling: 'no',
            //是否显示滚动条 no,yes,auto
            int: function () {
                $("#winClose").on('mouseenter',
                    function () {
                        $(this).css("background-image", "url()");
                    });
                $("#winClose").on('mouseleave',
                    function () {
                        $(this).css("background-image", "url()");
                    });
                $("#winClose").on('click',
                    function () {
                        $("#mask,#maskTop").fadeOut(function () {
                            $(this).remove();
                        });
                    });
            },
            open: function (width, height, src) {
                var iframeHeight = height;
                var marginLeft = width / 2;
                var marginTop = height / 2;
                var inntHtml = '';
                inntHtml += '<div id="mask" style="width:100%; height:100%; position:fixed; top:0; left:0; z-index:1999;background:#cccccc; filter:alpha(opacity=50); -moz-opacity:0.5; -khtml-opacity: 0.5; opacity:0.5;"></div>';
                inntHtml += '<div id="maskTop" style="width: ' + width + 'px; height: ' + height + 'px;  color: #333; position: fixed; top: 50%; left: 50%; margin-left: -' + marginLeft + 'px; margin-top: -' + marginTop + 'px; z-index: 2999; ">';
                inntHtml += '<div id="maskTitle" style="height: 0;position: relative;">';
                inntHtml += '<div id="winClose" style="width: 28px; height: 28px; cursor: pointer; position: absolute; top: -12px; right: -9px; background-image: url();"></div>';
                inntHtml += '</div>';
                inntHtml += '<iframe width="' + width + '" height="' + iframeHeight + '" frameborder="0" scrolling="' + this.scrolling + '" src="' + src + '"></iframe>';
                inntHtml += '</div>';
                $("body").append(inntHtml);
                this.int();
            },
            close: function () {
                $("#winClose").click();
            }
        },
        // 本地存储
        cookie: {
            get: function(cname) {
                var name = cname + '=';
                var ca = document.cookie.split(';');
                for(var i=0; i<ca.length; i++) {
                    var c = ca[i];
                    while (c.charAt(0)==' ') c = c.substring(1);
                    if (c.indexOf(name) != -1) return c.substring(name.length, c.length);
                }
                return '';
            },
            set: function(cname, cvalue, exdays, domain) {
                var d = new Date();
                d.setTime(d.getTime() + (exdays*24*60*60*1000));
                var expires = 'expires='+d.toUTCString();
                document.cookie = cname + '=' + cvalue + '; ' + expires + '; domain=' + domain + '; path=/';
            },
            del: function(name, domain) {
                this.set(name, '', -1, domain);
            }
        },
        session: {
            set: function(name, value) {
                if(Object.prototype.toString.call(value) === '[object Object]') value = JSON.stringify(value);
                sessionStorage.setItem(name, value)
            },
            get: function(name) {
                var value = sessionStorage.getItem(name);
                return utils.isJSON(value) ? JSON.parse(value) : value;
            },
            clear: function() {
                sessionStorage.clear();
            }
        },
        store: {
            set: function(key, val) {
                utils.session.set(glob.appName + ':' + key, val);
            },
            get: function(key) {
                return utils.session.get(glob.appName + ':' + key);
            },
            remove: function(key) {
                utils.session.remove(glob.appName + ':' + key);
            }
        }
    };
    var utils = new Utils();

    /**
     * == 提示 ==
     * */
    function Info() {

    }
    Info.prototype = {
        console: function(opt) {
            var _opt = {
                name: 'name',
                nStyle: { color: '#fff',  background: '#606060' },
                value: 'value',
                vStyle: { color: '#fff',  background: '#42C02E' }
            };
            utils.deepMerge(_opt, opt);
            console.log('%c ' + _opt.name + ' %c ' + _opt.value,
                'color:' + _opt.nStyle.color + ';background:' + _opt.nStyle.background + ';border-radius: 3px 0 0 3px',
                'color:' + _opt.vStyle.color + ';background:' + _opt.vStyle.background + ';padding-right: 5px;border-radius: 0 3px 3px 0')
        },
        show: function(name, value) {
            this.console({
                name: name,
                value: value
            })
        },
        error: function(msg) {
            // this.console({
            //     name: '错误',
            //     nStyle: { color: '#f00',  background: '#fff' },
            //     value: msg,
            //     vStyle: { color: '#f00',  background: '#fff' }
            // });
            throw new Error(name + version + ': ' + msg);
        },
        hint: function(msg) {
            this.console({
                name: 'warning',
                nStyle: { color: '#ffae47' },
                value: msg,
                vStyle: { color: '#fff', background: '#ffae47' }
            });
        }
    };
    var info = new Info();

    // 地址初始化
    (function urlInit() {
        var cyscid = utils.getQueryString('CYSCID'),
            cystid = utils.getQueryString('CYSTID'),
            urlSearch = utils.store.get('urlSearch');

        if(cyscid) {
            utils.store.set('cyscid', cyscid);
        }
        if(cystid) {
            utils.store.set( 'cystid', cystid);
        }
        if(!urlSearch) {
            utils.store.set('urlSearch', location.search);
        }
        $.extend(glob, {
            cyscid: utils.store.get('cyscid') || undefined,
            cystid: utils.store.get('cystid') || undefined,
            urlSearch: utils.store.get('urlSearch') || undefined,
        });
    })();

    // 构造函数合并
    function Mixin(recClass, giveClass) {
        if(arguments.length > 2) {
            for(var i = 2; i < arguments.length; ++i ) {
                var name = arguments[i];
                recClass.prototype[name] = giveClass.prototype[name];
            }
        }else {
            for(var key in giveClass.prototype) {
                if(!recClass.prototype[key]) {
                    recClass.prototype[key] = giveClass.prototype[key];
                }
            }
        }
    }

    /**
     * == 中间件，后期添加 到Utils ==
     * */
    var MidWare = function() {
        this.cache = [];
        this.options = {};
    };
    MidWare.prototype = {
        use: function(fn) {
            this.cache.push(fn);
            return this;
        },
        next: function(argument) {
            if(this.cache && this.cache.length > 0) {
                var ware = this.cache.shift();
                ware.call(this, this.options || {}, this.next.bind(this));
            }
        },
        handleRequest: function(options) {
            this.options = options;
            this.next();
        }
    };

    /**
     * == ajax 请求，Http 模块 ==
     * 与 Client 模块主要两点区别
     *      1、get、post 方法不再对 url 传参做 platform 拼接
     *      2、ajax 方法传参为对象，方法与 jquery 完全一致
     * */
    function Http() {

    }
    Http.prototype = {
        ajax: function (options) {
            if(glob.isDebug) {
                if(options.url.indexOf(glob.debugPath) !== -1) {
                    $.get(options.url + '.json', options.success);
                }else {
                    $.get(glob.host + glob.debugPath + options.url + '.json', options.success);
                }
            }else {
                $.ajax(utils.deepMerge({
                    dataType: 'json',
                    cache: false,
                    xhrFields: { withCredentials: true },
                    headers: {
                        'Authorization': glob.token,
                        'APP': glob.app,
                        'ACTIVITY': glob.activity,
                        'VERSIONCODE': glob.version,
                        'PLAT': glob.platform,
                        'CYSCID': glob.cyscid,
                        'CYSTID': glob.cystid
                    }
                }, options));
            }
        },
        common: function(type, url, variate, fun) {
            var data = {};
            if(typeof variate === 'function') {
                fun = variate;
            }else {
                data = variate;
            }
            url = glob.host + (glob.isDebug ? glob.debugPath + url : url);

            this.ajax({
                type: glob.isDebug ? 'GET' : type,
                url: url,
                data: data,
                success: fun
            });
        },
        get: function(url, variate, fun) {
            this.common('GET',  url, variate, fun);
        },
        post: function(url, variate, fun) {
            that.common('POST', url, variate, fun);
        }
    };
    var http = new Http();

    /**
     * == ajax 请求， client 模块 ==
     *  注：即将废弃，请使用 Http 模块
     * */
    function Client() {

    }
    Client.prototype = {
        ajax: function (type, url, variate, fun, plat) {
            switch (utils.objType(variate)) {
                case 'object':
                    if(variate.header) {
                        var header = variate.header;
                        delete variate.header;
                    }
                    if(variate.contentType) {
                        var contentType = variate.contentType;
                        delete variate.contentType;
                    }
                    var params = variate;
                    break;
                case 'function': fun = variate; break;
                case 'string': plat = variate; break;
                default: info.error('client.ajax使用错误');
            }
            $.ajax({
                type: type,
                url: url + (glob.isDebug ? '.json' : ''),
                data: params || {},
                dataType: 'json',
                cache: false,
                xhrFields: { withCredentials: true },
                contentType: contentType,
                headers: utils.objDelUndefined($.extend({
                    'Authorization': glob.token,
                    'APP': glob.app,
                    'ACTIVITY': glob.activity,
                    'VERSIONCODE': glob.version,
                    'PLAT': plat || glob.platform,
                    'CYSCID': glob.cyscid,
                    'CYSTID': glob.cystid
                }, header)),
                success: function(res) {
                    var code = res.code;
                    switch (code) {
                        case 0: alert('网络繁忙，请稍后再试'); break;     // 未知
                        // case 1012: alert('用户未登录'); break;
                        // case 1019: alert('登录状态检测失败'); break;
                        // case 1025: alert('短信登录检测失败'); break;
                        // case 1026: alert('短信自动登录检测失败'); break;
                        // case 1027: alert('微信公众号绑定登录检测失败'); break;
                        // case 1028: alert('微信活动绑定登录检测失败'); break;
                        // case 1317: alert('需要微信授权信息'); break;
                    }
                    fun(res)
                }
            })
        },
        common: function(type, url, variate, fun, plat) {
            switch (utils.objType(variate)) {
                case 'string': plat = variate; break;
                case 'object': var data = variate; break;
                case 'function': fun = variate; break;
            }
            var baseUrl = glob.host + (glob.isDebug ? glob.debugPath : '/' + (plat || glob.platform));
            this.ajax(glob.isDebug ? 'GET': type, baseUrl + url, data || {}, fun, plat);
        },
        get: function(url, variate, fun, plat) {
            this.common('GET',  url, variate, fun, plat);
        },
        post: function(url, variate, fun, plat) {
            this.common('POST', url, variate, fun, plat);
        }
    };
    var client = new Client();

    /**
     * == 用户通用模块 ==
     * */
    function User() {

    }
    User.prototype = {
        // 获取token
        getToken: function(fun) {
            client.get('/landing/init', function (res) {
                if(res.code === 10000) {
                    $.extend(glob, {
                        token: res.data.token,
                        activityInfo: res.data.activity,
                        appId: res.data.activity.wxId
                    });
                }else {
                    $.extend(_glob, {
                        code: res.code,
                        message: res.message
                    });
                    glob.isInitAlert && alert(res.message);
                }
                fun && fun(res);
            });
        },
        // 获取验证码
        getCode: function(variate, callBack) {        // variate 类型 string、number、object、function，通过类型判断
            var codeInit = 60,
                element = glob.ele,
                styleSheet = glob.style,
                $btnPhoneCode = $(element.btnPhoneCode),
                $inputPhone = $(element.inputPhone),
                phone = $inputPhone.val(),      // 手机号
                styleBefore = styleSheet.before,     // 默认样式，可点击
                styleAfter = styleSheet.after,   // 请求过程中、或倒计时中，不可点击
                type = utils.objType(variate),
                btnValue = $btnPhoneCode.text();    // 获取 发送验证码按钮 原内容

            switch (type) {
                case 'number':case 'string': phone = variate; break;
                case 'function': callBack = variate; break;
                default: break;
            }
            if(that.verify.phone(phone)) return alert(that.verify.phone(phone));
            $btnPhoneCode.html('发送中...').css(styleAfter);

            client.post('/core/zhpt/sendcode', {
                phone: phone
            }, function(res) {
                if(callBack) return callBack(res);
                if(res.code === 10000) {
                    $btnPhoneCode.css(styleAfter);
                    var codeNum = codeInit,
                        timer = setInterval(function() {
                            $btnPhoneCode.text(codeNum + 's');
                            if(codeNum <= 0) {
                                $btnPhoneCode.text(btnValue).css(styleBefore);
                                clearInterval(timer);
                            }
                            codeNum --;
                        }, 1000)
                }else {
                    $btnPhoneCode.text(btnValue).css(styleBefore);
                    alert(res.message);
                }
            }, 'phone');
        },
        // 手机号与验证码登陆
        loginPhone: function(variate, fun) {
            var element = glob.ele,
                styleSheet = glob.style,
                $inputPhone = $(element.inputPhone),
                $inputPhoneCode = $(element.inputPhoneCode),
                $btnPhone = $(element.btnPhone),
                btnValue = $btnPhone.text(),
                styleBefore = styleSheet.before,     // 默认样式，可点击
                styleAfter = styleSheet.after,   // 请求过程中、或倒计时中，不可点击
                inputInfo = { phone: $inputPhone.val(), code: $inputPhoneCode.val() };

            if(variate) {
                if(utils.objType(variate) === 'function') {
                    fun = variate;
                }else {
                    inputInfo = variate
                }
            }

            var errorPhone = that.verify.phone(inputInfo.phone),
                errorPhoneCode = that.verify.code(inputInfo.code);
            if(errorPhone) return alert(errorPhone);
            if(errorPhoneCode) return alert(errorPhoneCode);
            $btnPhone.text('登录中...').css(styleAfter);
            client.post(glob.urlCore + '/phonelogin', inputInfo, function(res) {
                if(fun) return fun(res);
                if(res.code === 10000) {
                    utils.reload();
                }else {
                    $btnPhone.text(btnValue).css(styleBefore);
                    alert(res.message)
                }
            }, 'phone');
        },
        // 获取用户信息
        getUserInfo: function(variate, fun) {
            if(typeof variate === 'function') {
                fun = variate;
            }else {
                var plat = variate;
            }
            client.get('/user/info', plat, function(res) {
                if(plat === 'wechat') {
                    if(res.code === 10000) {
                        $.extend(_glob, {
                            code: 1,
                            message: '微信信息获取成功',
                            wechatInfo: res.data
                        });
                    }else {
                        _glob.code = 2;
                        user.login('wechat');
                    }
                }else {
                    if(res.code === 10000) {
                        $.extend(_glob, {
                            code: 1,
                            message: '已登录',
                            userInfo: res.data
                        });
                    }else {
                        $.extend(_glob, {
                            code: 2,
                            message: '未登录',
                        });
                    }
                }
                fun && fun(res);
            })
        },
        // 查询用户是否是封停账号
        userStatus: function(fun) {
            ja.client.get('/user/isBaned', function(res) {
                fun && fun(res);
            })
        },
        // 登陆弹窗
        login: function(variate) {
            switch (_glob.code) {
                case 0:
                    break;
                case 1:
                    fun && typeof fun === 'function' && fun();
                    break;
                case 2:
                    var plat = typeof variate === 'string' ? variate : glob.platform
                        , url = glob.host + '/' + plat + glob.urlCore + '?callback=' + encodeURI(location.href);
                    switch (plat) {
                        case 'warframe': case 'changyou':case 'changyouwg':     // 星际战甲、畅游平台、海战世界
                            isMobile ? window.location.href = url : utils.win.open(496, 360, url);
                            break;
                        case 'cyou3':       // 橙柚
                            if(utils.isObject(variate)) url += '&' + $.param(variate);
                            isMobile ? window.location.href = url : utils.win.open(490, 470, url);
                            break;
                        case 'wechat':      // 微信
                            isWechat && (window.location.href = url);
                            break;
                        case 'phone':       // 手机号登录
                            user.loginPhone();
                            break;
                        default:
                            alert('暂时还没有该平台登陆功能');
                    }
                    break;
                case 1106:
                    alert('活动未开始');
                    break;
                case 1103:
                    alert('活动已结束');
                    break;
                case 1102:
                    alert('活动无效');
                    break;
                default:
            }
        },
        // 是否绑定微信
        wxIsBind: function(fun) {
            client.post('/auto/isbind', 'wechat', function(res) {
                fun && fun(res);
            })
        },
        // 微信绑定用户，自动登录
        wxAutoLogin: function(fun) {
            client.post('/auto/autologin', 'wechat', function(res) {
                fun && fun(res);
            })
        },
        // 登出
        logout: function (fun) {
            fun = typeof fun === 'function' ? fun : undefined;
            if(isWechat && glob.isWxLogin && glob.isUserInit) {   // 微信平台退出
                client.post('/auto/cancel', 'wechat', function(res) {
                    if(res.code === 10000) {
                        user.logoutAct(fun);
                    }else {
                        alert(res.message);
                    }
                })
            }else {
                user.logoutAct(fun);
            }
        },
        // 单独活动退出
        logoutAct: function(fun) {
            client.post(glob.urlCore + '/logout', function () {
                if(['changyou', 'warframe', 'wechat', 'changyouwg'].indexOf(glob.platform) !== -1) {
                    that.cookie.del('CASGTC', '.changyou.com');
                    // location.href = 'https://auth.changyou.com/logout.jsp?b=' + location.href.split("#")[0] + '&co=' + that.cookie.get("CASGTC");
                }
                fun || utils.reload();
            });
        }
    };
    var user = new User();

    /**
     * == 微信通用模块 ==
     * */
    function Wechat() {

    }
    Wechat.prototype = {
        // 微信初始化
        init: function(fun) {
            if(!glob.appId) {
                return info.error('微信初始化失败，没有得到 wxId');
            }
            $.getScript('https://res.wx.qq.com/open/js/jweixin-1.4.0.js', function () {
                $.get({
                    url: location.origin + '/wechat/web/' + glob.appId + '/config',
                    async: false,
                    success: function(data) {
                        if(data.config) {
                            wx.config({
                                debug: glob.isWxDebug ,     // 开启调试模式,调用的所有api的返回值会在客户端alert出来，若要查看传入的参数，可以在pc端打开，参数信息会通过log打出，仅在pc端时才会打印。
                                appId: data.config.appId,           // 必填，公众号的唯一标识
                                timestamp: data.config.timestamp,   // 必填，生成签名的时间戳
                                nonceStr: data.config.nonceStr,     // 必填，生成签名的随机串
                                signature: data.config.signature,   // 必填，签名，见附录1
                                jsApiList: [                        // 必填，需要使用的JS接口列表，所有JS接口列表见附录2
                                    'translateVoice',           // 识别音频并返回识别结果接口
                                    'onMenuShareTimeline',      // 分享到朋友圈
                                    'onMenuShareAppMessage',    // 分享给朋友
                                    'onMenuShareQQ',            // 分享到QQ
                                    'onMenuShareQZone',         // 分享到QQ空间
                                    'onMenuShareWeibo',         // 分享到腾讯微博
                                    'hideMenuItems',            // 批量隐藏功能按钮接口
                                    'hideAllNonBaseMenuItem'    // 隐藏所有非基础按钮接口
                                ]
                            });
                            fun && fun();
                        }else {
                            info.error('微信初始化失败，config接口异常，' + data.msg);
                        }
                    }
                });
            });
        },
        // 分享
        share: function(options) {
            if(isWechat) {
                var _options = {
                    type: 'link',
                    shareList: [
                        'onMenuShareTimeline',      // 分享到朋友圈
                        'onMenuShareAppMessage',    // 分享给朋友
                        'onMenuShareQQ',            // 分享到QQ
                        'onMenuShareWeibo',         // 分享到腾讯微博
                        'onMenuShareQZone'          // 分型到QQ空间
                    ]
                };
                $.extend(_options, options);
                var list = _options.shareList,
                    hideList = _options.hideMenuList;
                delete _options['shareList'];
                delete _options['hideMenuList'];
                wx.ready(function() {
                    for(var i in list) {
                        var shareType = list[i];
                        if(typeof wx[shareType] === 'function') {
                            wx[shareType](_options);
                        }
                    }
                    wx.hideMenuItems({
                        menuList: hideList
                    });
                })
            }
        }
    };
    var wechat = new Wechat();

    /**
     * == 活动开发，最终构造函数 ==
     * */
    var JoinActivity = function () {
        this.options = {
            app: undefined,             // 应用 初始化必传项
            activity: undefined,        // 活动 初始化必传项
            version: undefined,         // 版本 初始化必传项
            platform: undefined,        // 平台 初始化必传项

            type: glob.type,           // 版本固定后，通过 type 值区分之前之后项目

            isUserInit: true,           // 是否获取用户信息
            isWxLogin: false,           // 是否微信授权
            isWxInit: false,            // 是否微信初始化，开启后才能使用微信功能
            isWxDebug: false,           // 是否开启微信debug调试
            isWxStatus: false,          // 是否查询微信绑定账号
            isDebug: false,             // 是否开启调试模式
            debugPath: '/test/json',    // debug 请求基础路径
            isInitAlert: true,          // 是否关闭初始化弹窗，需要自定义活动状态 设置 false
            host: arrHost.indexOf(location.host) !== -1 ? location.protocol + '//join-activity.changyou.com' : location.origin,      // 接口请求域名，默认同域名
            wxShare: undefined,         // 微信分享内容
            ele: {
                inputPhone: '.input_phone',
                inputPhoneCode: '.input_phone_code',
                btnPhone: '.btn_phone',
                btnPhoneCode: '.btn_phone_code',
                btnWxBind: '.btn_wx_bind'
            },
            style: {
                before: { background: '', 'pointer-events': 'auto' },
                after: { background: '#9c9c9c', 'pointer-events': 'none' }
            },
            ready: function() {},   // 回调函数
        };
        this.glob = _glob;
        that = this;
    };
    JoinActivity.fn = JoinActivity.prototype = {
        config: function(options) {
            var opt = utils.deepMerge(this.options, options),           // 合并配参
                arrMust = ['app', 'activity', 'version', 'platform'],   // 初始化必填项，没有配置，给以提示
                show = new MidWare();

            // 统一输出
            function output(msg) {
                if(opt.isDebug) {
                    _glob.code = 1;
                }
                if(msg && typeof msg === 'string') {
                    alert(msg);
                }

                // glob.ready($.extend(_glob, {
                //     isLogin: _glob.code === 1
                // }));
                glob.ready(_glob);
                window[name] = new JoinActivity();
            }

            // 如果 platform 为 wechat，但不是在微信环境下，给以错误提示
            show.use(function(about, next) {
                if(opt.platform === 'wechat' && !isWechat) {
                    return output('请在微信中访问');
                }
                next();
            });

            // 必填项判断，并给以错误提示
            show.use(function(about, next) {
                info.show(name + '-version', version + '-' + opt.type || glob.type);  // 输出ja版本号
                for(var i in arrMust) {
                    var item = arrMust[i];
                    if(!opt[item]) {
                        return output(item + '为必填项');
                    }else {
                        info.show(item, opt[item]);
                    }
                }
                if(opt.type === 0) info.hint('config初始化配置请设置type为1');
                next();
            });

            // 无异常后，进行全局数据整理
            show.use(function(about, next) {
                $.extend(glob, opt, {
                    appName: [opt.app, opt.activity, opt.version, opt.platform].join('-'),      // 当前活动唯一标识
                    urlCore: opt.isDebug ? '/' + opt.platform : '/core/login/' + opt.app + '/' + opt.activity + '/' + opt.version       // 通用接口中间段
                });
                _glob.urlPath = '/' + opt.platform + '/' + opt.activity;                           // 活动接口中间段
                Mixin(JoinActivity, glob.type === 1 ? Http : Client);      // ajax 请求方法动态赋给 JoinActivity
                next();
            });

            // 开始接口请求，首先初始化，拿到token 和 活动状态
            show.use(function(about, next) {
                user.getToken(function(res) {
                    if(res.code === 10000) {
                        next();
                    }else {
                        output();
                    }
                })
            });

            // 先获取用户微信信息，如果得不到，会唤起微信授权
            show.use(function(about, next) {
                if(opt.platform === 'wechat' || (opt.isWxLogin && isWechat)) {
                    user.getUserInfo('wechat', function() {
                        about.isWx = true;
                        next();
                    });
                }else {
                    next();
                }
            });

            // 再获取用户账号信息，如果得不到，则为未登录状态
            show.use(function(about, next) {
                if(opt.isUserInit) {
                    user.getUserInfo(opt.platform, function() {
                        about.isPlatLogin = true;
                        next();
                    })
                }else
                    next();
            });

            // 再判断当前账号是否是封停账号（仅新天龙）
            show.use(function(about, next) {
                if(_glob.isLogin && glob.app === 'xtl') {
                    user.userStatus(function(res) {
                        _glob.isClosure = res.code === 3103;
                        next();
                    })
                }else {
                    next();
                }
            });

            // 再判断微信是否初始化、和微信分享
            show.use(function(about, next) {
                if(about.isWx && opt.isWxInit) {
                    wechat.init(function() {
                        if(opt.wxShare) wechat.share(opt.wxShare);
                    });
                    next();
                }else {
                    next();
                }
            });

            // 最终输出
            show.use(function(about, next) {
                output();
            });

            // 执行
            show.handleRequest();
        },
        ready: function(fun) {
            fun && fun(_glob)
        },
        // -----------------表单验证----------------
        verify: {
            reg: {
                phone: /^1[3456789]\d{9}$/,
                email: /^(\w-*\.*)+@(\w-?)+(\.\w{2,})+$/,           // 邮箱
                userName: /^[a-z0-9_-]{3,16}$/,                     // 用户名
                chineseName: /^[\u4E00-\u9FA5]{2,4}$/,              // 中文姓名
            },
            // 手机号
            phone: function (val) {
                if (!val) {
                    return '请填写手机号！';
                } else if (!val.match(this.reg.phone)) {
                    return '请输入正确的手机号！';
                } else {
                    return false;
                }
            },
            // 验证码
            code: function (val) {
                if (!val) {
                    return '请填写验证码！';
                } else if (val.length !== 6) {
                    return '验证码错误！'
                } else {
                    return false;
                }
            }
        },
        utils: utils,
        client: client,
        http: http,
        user: user,
        wx: wechat
    };

    Mixin(JoinActivity, Utils);
    Mixin(JoinActivity, User);
    Mixin(JoinActivity, Wechat);

    window[name] = new JoinActivity();

}(window));